package dongze.com.ckdj.activity;

import android.Manifest;
import android.content.ComponentName;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.ServiceConnection;
import android.content.pm.PackageManager;
import android.databinding.DataBindingUtil;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.RemoteException;
import android.provider.MediaStore;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.FileProvider;
import android.support.v7.app.AlertDialog;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.GridLayout;
import android.widget.ListView;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.Toast;

import java.io.File;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.inject.Inject;

import butterknife.BindView;
import butterknife.ButterKnife;
import dongze.com.ckdj.R;
import dongze.com.ckdj.adapter.EnclosureAdapter;
import dongze.com.ckdj.adapter.EnclosureListItem;
import dongze.com.ckdj.dagger.component.VehicleComponent;
import dongze.com.ckdj.data.entity.request.AddMassLossRecordRequestBody;
import dongze.com.ckdj.data.entity.response.InspectionSectionResponse;
import dongze.com.ckdj.data.entity.response.QueryMassLossRecordsResponse;
import dongze.com.ckdj.data.entity.response.QueryMassLossTypesResponse;
import dongze.com.ckdj.data.entity.response.QueryOtherPointsResponse;
import dongze.com.ckdj.data.entity.response.User;
import dongze.com.ckdj.data.entity.response.VehicleInformationDetail;
import dongze.com.ckdj.databinding.ActivityAddMassLossRecordBinding;
import dongze.com.ckdj.databinding.MassLossPictureItemBinding;
import dongze.com.ckdj.databinding.MassLossRecordItemBinding;
import dongze.com.ckdj.databinding.model.AddMassLossRecordModel;
import dongze.com.ckdj.databinding.model.MassLossImageItemModel;
import dongze.com.ckdj.databinding.model.MassLossPartModel;
import dongze.com.ckdj.databinding.model.MassLossRecordListModel;
import dongze.com.ckdj.databinding.model.ProcessingModel;
import dongze.com.ckdj.map.MapUtil;
import dongze.com.ckdj.persistence.DaoHelper;
import dongze.com.ckdj.persistence.dao.DaoSession;
import dongze.com.ckdj.persistence.dao.ImageDao;
import dongze.com.ckdj.persistence.dao.ServerUploadTask;
import dongze.com.ckdj.persistence.dao.ServerUploadTaskDao;
import dongze.com.ckdj.service.IImageUploadCallback;
import dongze.com.ckdj.service.IImageUploadService;
import dongze.com.ckdj.service.ImageUploadService;
import dongze.com.ckdj.service.ImageUploadTask;
import dongze.com.ckdj.ui.ImageUploadDialog;
import dongze.com.ckdj.ui.MassLossRadioGroup;
import dongze.com.ckdj.ui.StateDialog;
import dongze.com.ckdj.ui.TableView;
import dongze.com.ckdj.util.MyLog;
import dongze.com.ckdj.util.Util;
import io.reactivex.observers.DisposableObserver;

/**
 * 添加质损记录
 *
 * @author Renxiaoxiao 2017.08.11
 * @version 1.0
 */
public class AddMassLossRecordActivity extends ProgressableActivity {
    private static final String TAG = "AddMassLossRecordActiviy";
    private static final int PERMISSION_REQUEST = 2048;
    private static final int IMAGE_COUNT = 9;
    private static final int PHOTO_INTENT = 1024;
    private static final String IMAGE_PRIFIX = "massLoss";

    private String checkedType;
    private int requestCount;

    MapUtil mapUtil;

    @BindView(R.id.mass_loss_image_grid)
    GridLayout mGlImage;
    @BindView(R.id.mass_loss_type)
    MassLossRadioGroup mMassLossRg;
    @BindView(R.id.table_records)
    TableView mTlRecords;
    @BindView(R.id.list_enclosure)
    ListView mLvEnclosure;

    @Inject
    InspectionSectionResponse mInspectionSection;
    @Inject
    VehicleInformationDetail vehicleInformationDetail;
    @Inject
    User user;
    @Inject
    DaoSession daoSession;

    private List<EnclosureListItem> mEnclosureList = new ArrayList<>();
    private EnclosureAdapter adapter;
    private Map<String, String> informations = new HashMap<>();
    private Map<String, String> types = new HashMap<>();
    private ActivityAddMassLossRecordBinding binding;
    private AddMassLossRecordModel addMassLossRecordModel = new AddMassLossRecordModel();
    private MassLossPartModel massLossPartModel = new MassLossPartModel();
    private ProcessingModel processingModel = new ProcessingModel();
    MassLossImageItemModel[] imageModels = new MassLossImageItemModel[IMAGE_COUNT];
    File[] capturedImage = new File[IMAGE_COUNT];
    IImageUploadService mService;
    android.os.Handler handler;

    ServiceConnection mConn = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            MyLog.d(TAG, "onServiceConnected: ");
            mService = IImageUploadService.Stub.asInterface(service);
//            try {
//                mService.addCallback(mBinder);
//            } catch (RemoteException e) {
//                e.printStackTrace();
//            }
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {
            MyLog.d(TAG, "onServiceDisconnected: ");
//            try {
//                mService.removeCallback(mBinder);
//            } catch (RemoteException e) {
//                e.printStackTrace();
//            }
            mService = null;
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        handler = new Handler(getMainLooper());
        mapUtil = new MapUtil(getAppCompenent());
        binding = DataBindingUtil.inflate(getLayoutInflater(), R.layout.activity_add_mass_loss_record, null, false);
        binding.setAddMassLossRecord(addMassLossRecordModel);
        binding.setProcessing(processingModel);
        setContentView(binding.getRoot());
        ButterKnife.bind(this);

        bindService(new Intent(this, ImageUploadService.class), mConn, BIND_AUTO_CREATE);

        if (getComponent(VehicleComponent.class) != null) {
            getComponent(VehicleComponent.class).inject(this);
        } else {
            finish();
            return;
        }

        initData();

        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED) {
            doInit();
        } else {
            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, PERMISSION_REQUEST);
        }
    }

    private void initData() {
        Intent intent = getIntent();
        if (intent != null && intent.getExtras() != null) {
            informations.put("parentId", intent.getExtras().getString("parentId", ""));
            informations.put("childId", intent.getExtras().getString("childId", ""));
            informations.put("childName", intent.getExtras().getString("childName", ""));
            informations.put("enName", intent.getExtras().getString("enName", ""));
            informations.put("voyageNo", intent.getExtras().getString("voyageNo", ""));
            informations.put("model", intent.getExtras().getString("model", ""));
            informations.put("modelCode", intent.getExtras().getString("modelCode", ""));
            informations.put("uri", intent.getExtras().getString("uri", ""));
        } else {
            if (!isFinishing()) {
                new AlertDialog.Builder(this)
                        .setTitle("错误")
                        .setMessage("没有传递extras数据")
                        .setCancelable(false)
                        .setNegativeButton("退出", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                finish();
                            }
                        }).create()
                        .show();
            }
        }
    }

    @Override
    protected void onDestroy() {
        unbindService(mConn);
        mapUtil.dispose();
        super.onDestroy();
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        if (requestCode == PERMISSION_REQUEST) {
            if (Arrays.asList(permissions).contains(Manifest.permission.WRITE_EXTERNAL_STORAGE) && grantResults[0] == PackageManager.PERMISSION_DENIED) {
                new AlertDialog.Builder(this)
                        .setTitle("权限错误")
                        .setMessage("没有读写外部存储设备权限！！")
                        .setCancelable(false)
                        .setNegativeButton("退出", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                finish();
                            }
                        })
                        .create()
                        .show();
            } else {
                doInit();
            }
        }
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode >= PHOTO_INTENT && requestCode <= PHOTO_INTENT + IMAGE_COUNT) {
            int offset = requestCode - PHOTO_INTENT;
            if (resultCode == RESULT_OK) {

                if (capturedImage[offset] == null || !capturedImage[offset].exists()) {
                    Toast.makeText(this, "数据异常", Toast.LENGTH_SHORT).show();
                    return;
                }

//            try {
//                BitmapFactory.Options o = new BitmapFactory.Options();
//                o.inSampleSize = 2;
//                Bitmap b = BitmapFactory.decodeFile(capturedImage[offset].getAbsolutePath(), o);
//                imageModels[offset].setImageFile(new BitmapDrawable(getResources(), b));
//            } catch (Exception e) {
//                e.printStackTrace();
//            }
                imageModels[offset].setImageFile(capturedImage[offset].getAbsolutePath());
            } else {
                capturedImage[offset] = null;
            }
        } else {
            super.onActivityResult(requestCode, resultCode, data);
        }
    }

//    @Override
//    public boolean onCreateOptionsMenu(Menu menu) {
//        getMenuInflater().inflate(R.menu.mass_loss, menu);
//        return true;
//    }
//
//    @Override
//    public boolean onOptionsItemSelected(MenuItem item) {
//        if (item.getItemId() == R.id.save_record) {
//            saveMassLossRecord(informations.get("parentId"));
//        } else {
//            return super.onOptionsItemSelected(item);
//        }
//
//        return true;
//    }


    @Override
    protected void setActionBarButton() {
        mLeft.setVisibility(View.VISIBLE);
        mRight.setVisibility(View.VISIBLE);
        mRight.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                saveMassLossRecord(informations.get("parentId"));
            }
        });
    }

    private void initEnclosureList() {
        List<QueryOtherPointsResponse> list = getIntent().getParcelableArrayListExtra("list");
        if (list != null && list.size() > 0) {
            for (QueryOtherPointsResponse response : list) {
                mEnclosureList.add(new EnclosureListItem(response.getName_ch(), response.getName_en(), EnclosureListItem.Type.CHECKBOX, response.getSort()));
            }
//        mEnclosureList.add(new EnclosureListItem("车籍卡", "Car record card", EnclosureListItem.Type.CHECKBOX));
//        mEnclosureList.add(new EnclosureListItem("雨刷器", "The wiper", EnclosureListItem.Type.CHECKBOX));
//        mEnclosureList.add(new EnclosureListItem("备用钥匙", "Spare key", EnclosureListItem.Type.CHECKBOX));
//        mEnclosureList.add(new EnclosureListItem("简易钥匙", "Simple key", EnclosureListItem.Type.CHECKBOX));
//        mEnclosureList.add(new EnclosureListItem("牌照框", "AODI", EnclosureListItem.Type.CHECKBOX));
//        mEnclosureList.add(new EnclosureListItem("轮毂盖", "hubcaps", EnclosureListItem.Type.CHECKBOX));
            mEnclosureList.add(new EnclosureListItem("其他", "other", EnclosureListItem.Type.EDITTEXT, 65535));
        }
        for (EnclosureListItem item : mEnclosureList) {
            MyLog.i(TAG, "initEnclosureList: " + item.getChText() + " " + item.getEnText() + " " + item.getType().toData());
        }
        MyLog.i(TAG, "initEnclosureList: size = " + mEnclosureList.size());
    }

    private void doInit() {
        String parentId = informations.get("parentId");
        if ("14".equals(parentId)) {
            binding.setPart(massLossPartModel);
            massLossPartModel.part.set(informations.get("childName"));
            addMassLossRecordModel.include1.set(false);
            addMassLossRecordModel.include2.set(true);
            addMassLossRecordModel.include3.set(false);
        } else if ("15".equals(parentId)) {
            initEnclosureList();
            adapter = new EnclosureAdapter(mEnclosureList);
            mLvEnclosure.setAdapter(adapter);
            addMassLossRecordModel.include1.set(false);
            addMassLossRecordModel.include2.set(false);
            addMassLossRecordModel.include3.set(true);
        } else {
            addMassLossRecordModel.include1.set(true);
            addMassLossRecordModel.include2.set(false);
            addMassLossRecordModel.include3.set(false);
            getMassLossTypes(informations.get("childId"));
            getMassLossRecords(vehicleInformationDetail.getVin());
        }

//        getMassLossRecords("1235555555555");

        buildMassLossImage();
        newMassLossRecord(parentId);
    }

    // 新建质损记录
    private void newMassLossRecord(String parentId) {
        addMassLossRecordModel.vin.set(vehicleInformationDetail.getVin());
        if ("14".equals(parentId)) {
            addMassLossRecordModel.remark.set(null);
            addMassLossRecordModel.point.set("配件");
        } else if ("15".equals(parentId)) {
            adapter.notifyDataSetChanged();
            addMassLossRecordModel.remark.set(null);
            addMassLossRecordModel.point.set("附件包");
        } else {
            addMassLossRecordModel.point.set(informations.get("childName"));
            addMassLossRecordModel.level.set(getResources().getString(R.string.level_normal));
            addMassLossRecordModel.source.set("默认");
            addMassLossRecordModel.type.set(checkedType);
            addMassLossRecordModel.position.set(Arrays.asList(new String[]{"5#"}));
            addMassLossRecordModel.remark.set(null);
        }

        for (MassLossImageItemModel m :
                imageModels) {
            m.setImageFile(null);
        }
    }

    // 保存质损记录
    private void saveMassLossRecord(String parentId) {
        if (!"14".equals(parentId) && !"15".equals(parentId)) {
            StringBuilder errString = new StringBuilder();
            if (addMassLossRecordModel.level.get() == null || addMassLossRecordModel.level.get().isEmpty() ||
                    addMassLossRecordModel.type.get() == null || addMassLossRecordModel.type.get().isEmpty()) {
                errString.append("质损原因数据不正确\n");
            }

            if (addMassLossRecordModel.level.get() == null
                    || addMassLossRecordModel.level.get().isEmpty()) {
                errString.append("请选择质损程度\n");
            }

            if (addMassLossRecordModel.position.get() == null
                    || addMassLossRecordModel.position.get().isEmpty()) {
                errString.append("请选择质损位置\n");
            }

            if (addMassLossRecordModel.type.get() == null
                    || addMassLossRecordModel.type.get().isEmpty()) {
                errString.append("请选择质损类型\n");
            }

            if (TextUtils.equals(addMassLossRecordModel.type.get(), "其它") && TextUtils.isEmpty(addMassLossRecordModel.remark.get())) {
                errString.append("备注不能为空\n");
            }

            if (!errString.toString().isEmpty()) {
                new AlertDialog.Builder(this)
                        .setTitle("数据不完整")
                        .setMessage(errString)
                        .create()
                        .show();
                return;
            }
        }

        commitRecord(parentId);
    }

    // 提交质损记录
    private void commitRecord(String parentId) {
        final AddMassLossRecordRequestBody body = new AddMassLossRecordRequestBody();
//        body.setVin("1235555555555");
//        body.setBrand_name("奔驰");
//        body.setVoyage_no("航次1");
//        body.setuUser("刘备");
//        body.setResist_place("港检");
        body.setVin(vehicleInformationDetail.getVin());
        body.setBrand_name(vehicleInformationDetail.getBrand_name());
        body.setVoyage_no(informations.get("voyageNo"));
        body.setModel(informations.get("model"));
        body.setModel_code(informations.get("modelCode"));
        if ("14".equals(parentId)) {
            body.setDescription_cn(informations.get("childName") + (TextUtils.isEmpty(addMassLossRecordModel.remark.get()) ? "" : ("-" + addMassLossRecordModel.remark.get())));
            body.setDescription_en(informations.get("enName"));
            body.setPosition("配件");
            body.setLoss_level(getResources().getString(R.string.level_normal));
            body.setLoss_place("0#");
        } else if ("15".equals(parentId)) {
            String[] reason = ((EnclosureAdapter) mLvEnclosure.getAdapter()).buildReason();
            MyLog.i(TAG, "saveMassLossRecord: 中文:" + reason[0]);
            MyLog.i(TAG, "saveMassLossRecord: 英文:" + reason[1]);
            body.setDescription_cn("附件包-" + reason[0] + (TextUtils.isEmpty(addMassLossRecordModel.remark.get()) ? "" : ("-" + addMassLossRecordModel.remark.get())));
            body.setDescription_en("Accessories bag-" + reason[1]);
            body.setPosition("附件包");
            body.setLoss_level(getResources().getString(R.string.level_normal));
            body.setLoss_place("0#");
        } else {
            body.setDescription_en(informations.get("enName") + "-" + types.get(addMassLossRecordModel.type.get()));
            body.setPosition(informations.get("childName"));
            body.setLoss_level(addMassLossRecordModel.level.get());

            if (TextUtils.equals(addMassLossRecordModel.type.get(), "其它")) {
                body.setDescription_cn(informations.get("childName") + "-" + addMassLossRecordModel.remark.get());
            } else {
                body.setDescription_cn(informations.get("childName") + "-" + addMassLossRecordModel.type.get() + (TextUtils.isEmpty(addMassLossRecordModel.remark.get()) ? "" : ("-" + addMassLossRecordModel.remark.get())));
            }

            List<String> arr = addMassLossRecordModel.position.get();
            String value = arr.get(0);
            for (int i = 1; i < arr.size(); i++) {
                value += "," + arr.get(i);
            }
            body.setLoss_place(value);
        }

        body.setUser_name(user.getUser_name());
        body.setResist_place(mInspectionSection.getNode_name());
        body.setRemark(addMassLossRecordModel.remark.get());
        body.setResource(addMassLossRecordModel.source.get());

        MyLog.i(TAG, "commitRecord: request:" + body.toString());

        mapUtil.addMassLossRecord(body, new DisposableObserver<Long>() {
            @Override
            protected void onStart() {
                super.onStart();
                doProcessing();
            }

            @Override
            public void onNext(Long value) {
                try {
                    if (Util.DISABLE.equals(Util.getPreference(getApplicationContext(), Util.PREF_UPLOAD_BACKGROUND, Util.DISABLE))) {
                        doUploadImage(value);
                    } else {
                        saveUploadImageRecordToService(value);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                    new AlertDialog.Builder(AddMassLossRecordActivity.this)
                            .setMessage("上传图片失败！！！！" + e.getMessage())
                            .create()
                            .show();
                }
            }

            @Override
            public void onError(Throwable e) {
                finishProcessing();
                new AlertDialog.Builder(AddMassLossRecordActivity.this)
                        .setMessage("文本数据上传失败。\n" + e.getMessage())
                        .create()
                        .show();
            }

            @Override
            public void onComplete() {
                finishProcessing();
            }
        });
    }

    // 照片网格
    private void buildMassLossImage() {
        for (int i = 0; i < IMAGE_COUNT; i++) {
            final int value = i;
            final MassLossImageItemModel image = new MassLossImageItemModel();
            image.setVisibility(View.VISIBLE);
            image.setOnNewClicked(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (!Util.checkCapturePermission(AddMassLossRecordActivity.this))
                        return;

                    File file = Util.getImageFile(IMAGE_PRIFIX);

                    Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);

                    int currentapiVersion = android.os.Build.VERSION.SDK_INT;
                    if (currentapiVersion < 24) {
                        intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(file));
                        startActivityForResult(intent, PHOTO_INTENT + value);
                    } else {
                        Uri uri = FileProvider.getUriForFile(AddMassLossRecordActivity.this, "dongze.com.ckdj.fileprovider", file);
                        intent.putExtra(MediaStore.EXTRA_OUTPUT, uri);
                        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
                        startActivityForResult(intent, PHOTO_INTENT + value);
                    }
                    capturedImage[value] = file;
                }
            });
            image.setOnDeleteClicked(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    image.setImageFile(null);
                    if (capturedImage[value] != null)
                        Util.deleteFile(capturedImage[value].getAbsolutePath());
                    capturedImage[value] = null;
                }
            });
            image.setOnImageClicked(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Util.ViewImage(AddMassLossRecordActivity.this, capturedImage[value]);
                }
            });
            imageModels[i] = image;

            MassLossPictureItemBinding binding1 = DataBindingUtil.inflate(getLayoutInflater(), R.layout.mass_loss_picture_item, mGlImage, false);
            binding1.setMassLossImageItem(imageModels[i]);
            int width = getResources().getDisplayMetrics().widthPixels / 3-
                    getResources().getDimensionPixelSize(R.dimen.content_padding);
            GridLayout.LayoutParams params = new GridLayout.LayoutParams(new ViewGroup.LayoutParams(
                    width, width));
//            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
//                params.columnSpec = GridLayout.spec(i % 3, 1f);
//                params.rowSpec = GridLayout.spec(i / 3, 1f);
//            }
            mGlImage.addView(binding1.getRoot(), params);
        }
    }

    //使用service，离线上传
    private void saveUploadImageRecordToService(Long massLossRecord) {
        final List<File> images = new ArrayList<>(capturedImage.length);

        for (int i = 0; i < capturedImage.length; i++) {
            if (capturedImage[i] != null)
                images.add(capturedImage[i]);
        }

        if (images.size() == 0) {
            finish();
            return;
        }

        if (mService != null) {
            try {
                for (int i = 0; i < images.size(); i++) {
                    mService.addTask(DaoHelper.createMassLossTask(daoSession,
                            vehicleInformationDetail.getVin(),
                            user.getUser_name(),
                            String.valueOf(massLossRecord),
                            "img" + String.format("%02d", i + 1/*从1开始*/),
                            images.get(i).getAbsolutePath()));
                }
            } catch (RemoteException e) {
                e.printStackTrace();
            }
        } else {
            new AlertDialog.Builder(this)
                    .setTitle("错误")
                    .setMessage("图片上传服务不可用,请重启app并重新录入数据！")
                    .create()
                    .show();
        }
    }

    //同步上传
    private void doUploadImage(final Long massLossRecord) {
        final List<File> images = new ArrayList<>(capturedImage.length);
        final List<ImageUploadTask> tasks = new ArrayList<>();

        for (int i = 0; i < capturedImage.length; i++) {
            if (capturedImage[i] != null) {
                images.add(capturedImage[i]);
            }
        }

        if (images.size() == 0) {
            finish();
            return;
        }

        for (int i = 0; i < images.size(); i++) {
            ImageUploadTask task = DaoHelper.createMassLossTask(daoSession,
                    vehicleInformationDetail.getVin(),
                    user.getUser_name(),
                    String.valueOf(massLossRecord),
                    "img" + String.format("%02d", i + 1/*从1开始*/),
                    images.get(i).getAbsolutePath());
            tasks.add(task);
        }

        ImageUploadDialog imageUploadDialog = new ImageUploadDialog(AddMassLossRecordActivity.this, tasks, images, null);
        imageUploadDialog.setOnDismissListener(new DialogInterface.OnDismissListener() {
            @Override
            public void onDismiss(DialogInterface dialog) {
                for (MassLossImageItemModel model :
                        imageModels) {
                    model.setImageFile(null);
                }

                for (int i = 0; i < capturedImage.length; i++) {
                    capturedImage[i] = null;
                }

                finish();
            }
        });
        imageUploadDialog.show();
    }

    private void updateImageRecord(final StateDialog dialog, final ImageUploadTask task, String massrecord, String imageIndex, final List<File> images, final IImageUploadCallback callback) {
        ServerUploadTask serverUploadTask = daoSession.getServerUploadTaskDao().queryBuilder().where(ServerUploadTaskDao.Properties.Id.eq(task.getId())).unique();

        if (serverUploadTask == null) {
            MyLog.e(TAG, "updateImageRecord: serverUploadTask id not exist");
            return;
        }

        mapUtil.updateMassLossImageRecord(
                massrecord,
                imageIndex,
                serverUploadTask.getImage().getServerPath(),
                informations.get("user_name"),
                new DisposableObserver<String>() {
                    @Override
                    protected void onStart() {
                        super.onStart();
                        dialog.addStateMessage("更新图片信息：" + task.getId());
                    }

                    @Override
                    public void onNext(String value) {
                        if ("success".equals(value)) {
                            dialog.addStateMessage(task.getId() + "更新信息OK。");


                            int founded = -1;
                            ImageDao imageDao = daoSession.getImageDao();
                            for (int i = 0; i < images.size(); i++) {
                                if (imageDao.queryBuilder().where(ImageDao.Properties.FilePath.eq(images.get(i).getAbsolutePath())).unique() != null) {
                                    founded = i;
                                    break;
                                }
                            }

                            if (founded != -1) {
                                images.remove(founded);
                            } else {
                                //  跟当前任务没关系
                                //dialog.addStateMessage("异常：上传的图片再当前任务图片列表中未找到！！！！");
                            }

                            if (images.size() == 0) {
                                dialog.addStateMessage("任务完成");
                                dialog.finish();
                                try {
                                    mService.removeCallback(callback);
                                } catch (RemoteException e) {
                                    e.printStackTrace();
                                }
                            }
                        } else {
                            dialog.critical(task.getId() + "更新信息失败");
                        }
                    }

                    @Override
                    public void onError(Throwable e) {
                        dialog.critical(task.getId() + "更新信息失败，" + e.getMessage());
                    }

                    @Override
                    public void onComplete() {

                    }
                });
    }


    /**
     * 根据车架号查询
     *
     * @param vinNo
     */
    private void getMassLossRecords(String vinNo) {
        mapUtil.getMassLossRecords(vinNo, new DisposableObserver<List<QueryMassLossRecordsResponse>>() {
            @Override
            protected void onStart() {
                requestCount++;
                if (!processingModel.visible.get()) {
                    processingModel.visible.set(true);
                }
            }

            @Override
            public void onNext(List<QueryMassLossRecordsResponse> value) {
                mTlRecords.removeAllViews();
                MassLossRecordListModel title = new MassLossRecordListModel();
                title.type.set("质损原因");
                title.level.set("质损程度");
                title.point.set("质损位置");
                title.link.set("点检环节");
                addMassLossRecordList(title);
                MyLog.i(TAG, "onNext: 质损记录条数 = " + value.size());
                if (value != null && value.size() > 0) {
                    for (QueryMassLossRecordsResponse response : value) {
                        MassLossRecordListModel model = new MassLossRecordListModel();
                        MyLog.i(TAG, "onNext1: " + response.getLoss_region());
                        model.type.set(response.getLoss_reason());
                        model.level.set(response.getLoss_level());
                        model.point.set(response.getLoss_region());
                        model.link.set(response.getRegist_place());
                        addMassLossRecordList(model);
                    }
                } else {
                    mTlRecords.addView(getLayoutInflater().inflate(R.layout.no_content, mTlRecords, false));
                }
            }

            @Override
            public void onError(Throwable e) {
                requestCount--;
                if (requestCount == 0)
                    processingModel.visible.set(false);
                if (!isFinishing()) {
                    new android.support.v7.app.AlertDialog.Builder(AddMassLossRecordActivity.this)
                            .setTitle("错误" + e.getMessage())
                            .setMessage(e.getLocalizedMessage())
                            .create()
                            .show();
                }
            }

            @Override
            public void onComplete() {
                requestCount--;
                if (requestCount == 0)
                    processingModel.visible.set(false);
            }
        });
    }

    private void addMassLossRecordList(MassLossRecordListModel model) {
        MassLossRecordItemBinding binding = DataBindingUtil.inflate(LayoutInflater.from(this), R.layout.mass_loss_record_item, mTlRecords, false);
        binding.setMassLossListModel(model);
        mTlRecords.addView(binding.getRoot());
    }

    /**
     * 获取子部位的质损类型
     *
     * @param childId 子部位id
     */
    private void getMassLossTypes(String childId) {
        mapUtil.getMassLossTypes(childId, new DisposableObserver<List<QueryMassLossTypesResponse>>() {
            @Override
            protected void onStart() {
                super.onStart();
                requestCount++;
                if (!processingModel.visible.get()) {
                    processingModel.visible.set(true);
                }
            }

            @Override
            public void onNext(List<QueryMassLossTypesResponse> value) {
                if (value != null && value.size() > 0) {
                    mMassLossRg.removeAllViews();
                    checkedType = value.get(0).getLoss_type_ch();
//                            addMassLossRecordModel.type.set(checkedType);
//                            layoutParams.setMargins(10, 10, 10, 10);
                    for (QueryMassLossTypesResponse type : value) {
                        MyLog.i(TAG, "onNext: 中文: " + type.getLoss_type_ch() + " 英文: " + type.getLoss_type_en());
                        types.put(type.getLoss_type_ch(), type.getLoss_type_en());
                        RadioButton button = new RadioButton(AddMassLossRecordActivity.this);
                        RadioGroup.LayoutParams layoutParams = new RadioGroup.LayoutParams(RadioGroup.LayoutParams.WRAP_CONTENT, RadioGroup.LayoutParams.WRAP_CONTENT);
                        button.setText(type.getLoss_type_ch());
                        mMassLossRg.addView(button, layoutParams);
                    }
                }
            }

            @Override
            public void onError(Throwable e) {
                MyLog.e(TAG, "onError: ", e);
                requestCount--;
                if (requestCount == 0)
                    processingModel.visible.set(false);
                if (!isFinishing()) {
                    new android.support.v7.app.AlertDialog.Builder(AddMassLossRecordActivity.this)
                            .setTitle("错误" + e.getMessage())
                            .setMessage(e.getLocalizedMessage())
                            .create()
                            .show();
                }
            }

            @Override
            public void onComplete() {
                requestCount--;
                if (requestCount == 0)
                    processingModel.visible.set(false);
            }
        });
    }

    /**
     * 启动添加质损记录
     *
     * @param context
     * @param childId
     * @param childName
     * @param enName
     * @param voyage
     * @param model
     * @param code
     * @param uri
     */
    public static void actionStart(Context context, String parentId, String childId, String childName, String enName,
                                   String voyage, String model, String code, String uri) {
        Intent intent = new Intent(context, AddMassLossRecordActivity.class);
        intent.putExtra("parentId", parentId);
        intent.putExtra("childId", childId);
        intent.putExtra("childName", childName);
        intent.putExtra("enName", enName);
        intent.putExtra("voyageNo", voyage);
        intent.putExtra("model", model);
        intent.putExtra("modelCode", code);
        intent.putExtra("uri", uri);
        context.startActivity(intent);
    }
}
